using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using Common.Enum;
using Common.NotifyEvent;
using Define;
using device;
using SProject;
using SProject.BasicInformation;
using SProject.Paramter;
using SProject.Program;
using SProject.Rule;
using SSettings;
using SSettings.ExperimentColumn;

namespace SExperiment
{
    [Serializable]
    public class Experiment : NotifyPropertyChanged
    {
        private const string CSVKEY_WellNo = "WellNo";

        private const string CSVKEY_TestPrj = "TestPrj";

        private const string CSVKEY_TubeNo = "TubeNo";

        private const string CSVKEY_Type = "Type";

        private const string CSVKEY_Property = "Property";

        private const string CSVKEY_ReTubeNo = "ReTubeNo";

        private const string CSVKEY_Barcode = "Barcode";

        private const string CSVKEY_PName = "PName";

        private const string CSVKEY_PID = "PID";

        private const string CSVKEY_PSex = "PSex";

        private const string CSVKEY_PAge = "PAge";

        private const string CSVKEY_PSpecimen = "PSpecimen";

        private const string CSVKEY_PSpecimenDate = "PSpecimenDate";

        private const string CSVKEY_PDoctor = "PDoctor";

        private const string CSVKEY_POffice = "POffice";

        private const string CSVKEY_PDiagnosis = "PDiagnosis";

        private const string CSVKEY_PCaseID = "PCaseID";

        private const string CSVKEY_PBedID = "PBedID";

        private const string CSVKEY_PInPatientID = "PInPatientID";

        private const string CSVKEY_POutPatientID = "POutPatientID";

        private const string CSVKEY_PRemark = "PRemark";

        private const string CSVKEY_SName = "SName";

        private const string Key_WellPlate = "[WELLPLATE]";

        public static DateTime CreateTime = DateTime.Now;

        public static string FileExt = "pcr";

        public static string BakExt = "bak";

        public static string FileStdExt = "std";

        public static string FileTemplateExt = "tmp";

        public static string FileTemplateDotExt = "." + FileTemplateExt;

        public static string LastTempateName = Path.GetTempPath() + "lastexperiment." + FileTemplateExt;

        private string _DefaultPath = string.Empty;

        private EProjectType _Type = ConfigSettings.GetInstance().MemorySettings.Type;

        private string _Name = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");

        private string _Operator = "";

        private string _Operator2 = "";

        private string _Auditor = "";

        private string _Note = "";

        private string _UpdateVersion;

        private string _RunVersion;

        private string _DumpVersion;

        private string _Password;

        public string _CSVContent;

        private string _PreTreatment;

        private string _Simple_Name = string.Empty;

        private string _TemplateRemarks = string.Empty;

        private byte[] _Image;

        public Hashtable BadPoints = new Hashtable();

        private bool _MarkBadPoint;

        private Device _Device = new Device();

        private bool _CanUseModelA = true;

        private bool _CanUseModelB = true;

        private bool _UseModelA = true;

        private bool _UseModelB = true;

        private bool _UseHotBonnet = ConfigSettings.GetInstance().MemorySettings.UseHotBonnet;

        private ETemperatureControlMode _TemperatureControlMode = ConfigSettings.GetInstance().MemorySettings.TemperatureControlMode;

        private EScanMode _ScanMode = ConfigSettings.GetInstance().MemorySettings.ScanMode;

        private EExperimentStatus _Status;

        private PCRProgram _Program;

        private List<Well> _Wells = new List<Well>();

        private Subset _CurrentSubset;

        private ObservableCollection<Subset> _Subsets = new ObservableCollection<Subset>();

        private EColorMode _ColorMode;

        private ExperimentSetting _ExperimentSetting = ConfigSettings.GetInstance().ExperimentSetting.Clone();

        private int _CustomCount;

        private GridColumns _GridColumns;

        private List<Well> _ModleAWells = new List<Well>();

        private List<Well> _ModleBWells = new List<Well>();

        private bool _IsRegisterDeviceRunEvent;

        private string datPath = Utility.GetApplicationPath() + "data.dat";

        private int indexCompany = 10001;

        private int indexSN = 20001;

        private string encryptKey = "SlanSNEncry";

        public string DefaultPath
        {
            get
            {
                if (string.IsNullOrEmpty(_DefaultPath))
                {
                    _DefaultPath = _ExperimentSetting.FixExperimentPath;
                }
                return _DefaultPath;
            }
            set
            {
                _DefaultPath = value;
            }
        }

        public string FilePath
        {
            get
            {
                return Path.Combine(DefaultPath, Name + "." + FileExt);
            }
        }
        /// <summary>
        /// 项目类型
        /// </summary>
        public EProjectType Type
        {
            get
            {
                return _Type;
            }
            set
            {
                if (_Type != value)
                {
                    _Type = value;
                    Init();
                    OnPropertyChanged("Type");
                }
            }
        }

        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (!(_Name == value))
                {
                    _Name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        public string Operator
        {
            get
            {
                return _Operator;
            }
            set
            {
                if (!(_Operator == value))
                {
                    _Operator = value;
                    OnPropertyChanged("Operator");
                }
            }
        }

        public string Operator2
        {
            get
            {
                return _Operator2;
            }
            set
            {
                if (!(_Operator2 == value))
                {
                    _Operator2 = value;
                    OnPropertyChanged("Operator2");
                }
            }
        }

        public string Auditor
        {
            get
            {
                return _Auditor;
            }
            set
            {
                if (!(_Auditor == value))
                {
                    _Auditor = value;
                    OnPropertyChanged("Auditor");
                }
            }
        }

        public string Note
        {
            get
            {
                return _Note;
            }
            set
            {
                if (!(_Note == value))
                {
                    _Note = value;
                    OnPropertyChanged("Note");
                }
            }
        }

        public string UpdateVersion
        {
            get
            {
                return _UpdateVersion;
            }
            private set
            {
                if (!(_UpdateVersion == value))
                {
                    _UpdateVersion = value;
                }
            }
        }

        public string RunVersion
        {
            get
            {
                return _RunVersion;
            }
            private set
            {
                if (!(_RunVersion == value))
                {
                    _RunVersion = value;
                }
            }
        }

        public string DumpVersion
        {
            get
            {
                return _DumpVersion;
            }
            private set
            {
                if (!(_DumpVersion == value))
                {
                    _DumpVersion = value;
                }
            }
        }

        public string Password
        {
            get
            {
                return _Password;
            }
            set
            {
                if (!(_Password == value))
                {
                    _Password = value;
                    OnPropertyChanged("Password");
                }
            }
        }

        public string CSVContent
        {
            get
            {
                return _CSVContent;
            }
            set
            {
                if (!(_CSVContent == value))
                {
                    _CSVContent = value;
                    OnPropertyChanged("CSVContent");
                }
            }
        }

        public string PreTreatment
        {
            get
            {
                return _PreTreatment;
            }
            set
            {
                if (!(_PreTreatment == value))
                {
                    _PreTreatment = value;
                    OnPropertyChanged("PreTreatment");
                }
            }
        }

        public string Simple_Name
        {
            get
            {
                return _Simple_Name;
            }
            set
            {
                if (!(_Simple_Name == value))
                {
                    _Simple_Name = value;
                    OnPropertyChanged("Simple_Name");
                }
            }
        }

        public string TemplateRemarks
        {
            get
            {
                return _TemplateRemarks;
            }
            set
            {
                if (!(_TemplateRemarks == value))
                {
                    _TemplateRemarks = value;
                    OnPropertyChanged("TemplateRemarks");
                }
            }
        }

        public byte[] Image
        {
            get
            {
                return _Image;
            }
            set
            {
                if (_Image != value)
                {
                    _Image = value;
                }
            }
        }

        public bool MarkBadPoint
        {
            get
            {
                return _MarkBadPoint;
            }
            set
            {
                if (_MarkBadPoint != value)
                {
                    _MarkBadPoint = value;
                    OnPropertyChanged("MarkBadPoint");
                }
            }
        }

        public Device Device
        {
            get
            {
                return _Device;
            }
            set
            {
                if (_Device != value)
                {
                    _Device = value;
                    OnPropertyChanged("Device");
                }
            }
        }

        public bool CanUseModelA
        {
            get
            {
                return _CanUseModelA;
            }
            set
            {
                if (_CanUseModelA != value)
                {
                    _CanUseModelA = value;
                    if (!_CanUseModelA)
                    {
                        UseModelA = false;
                    }
                    OnPropertyChanged("CanUseModelA");
                }
            }
        }

        public bool CanUseModelB
        {
            get
            {
                return _CanUseModelB;
            }
            set
            {
                if (_CanUseModelB != value)
                {
                    _CanUseModelB = value;
                    if (_Device.Model == Device.DeviceModel_48P || _Device.Model == Device.DeviceModel_24P)
                    {
                        _CanUseModelB = false;
                    }
                    if (!_CanUseModelB)
                    {
                        UseModelB = false;
                    }
                    OnPropertyChanged("CanUseModelB");
                }
            }
        }

        public bool UseModelA
        {
            get
            {
                return _UseModelA;
            }
            set
            {
                if (_UseModelA != value)
                {
                    _UseModelA = value;
                    MustUseModelA();
                    UpdataSubsetAll();
                    OnPropertyChanged("UseModelA");
                }
            }
        }

        public bool UseModelB
        {
            get
            {
                return _UseModelB;
            }
            set
            {
                if (_UseModelB != value)
                {
                    _UseModelB = value;
                    MustUseModelB();
                    UpdataSubsetAll();
                    OnPropertyChanged("UseModelB");
                }
            }
        }

        public bool UseHotBonnet
        {
            get
            {
                return _UseHotBonnet;
            }
            set
            {
                if (_UseHotBonnet != value)
                {
                    _UseHotBonnet = value;
                    OnPropertyChanged("UseHotBonnet");
                }
            }
        }

        public ETemperatureControlMode TemperatureControlMode
        {
            get
            {
                return _TemperatureControlMode;
            }
            set
            {
                if (_TemperatureControlMode != value)
                {
                    _TemperatureControlMode = value;
                    OnPropertyChanged("TemperatureControlMode");
                }
            }
        }

        public EScanMode ScanMode
        {
            get
            {
                return _ScanMode;
            }
            set
            {
                if (_ScanMode != value)
                {
                    _ScanMode = value;
                    OnPropertyChanged("ScanMode");
                }
            }
        }

        public EExperimentStatus Status
        {
            get
            {
                return _Status;
            }
            set
            {
                if (_Status == value)
                {
                    return;
                }
                _Status = value;
                if (_Status == EExperimentStatus.Completed)
                {
                    DeleteTemporaryFile();
                    UnLinkProject();
                    if (Type == EProjectType.HRM || Type == EProjectType.AD)
                    {
                        ColorMode = EColorMode.Result;
                    }
                }
                OnPropertyChanged("Status");
            }
        }

        public PCRProgram Program
        {
            get
            {
                return _Program;
            }
            set
            {
                if (_Program != value)
                {
                    _Program = value;
                    OnPropertyChanged("Program");
                }
            }
        }

        public List<Well> Wells
        {
            get
            {
                return _Wells;
            }
            set
            {
                if (_Wells != value)
                {
                    _Wells = value;
                    InitModelAB();
                    OnPropertyChanged("Wells");
                }
            }
        }

        public Subset CurrentSubset
        {
            get
            {
                return _CurrentSubset;
            }
            set
            {
                if (_CurrentSubset != value)
                {
                    _CurrentSubset = value;
                    OnPropertyChanged("CurrentSubset");
                }
            }
        }

        public ObservableCollection<Subset> Subsets
        {
            get
            {
                return _Subsets;
            }
        }

        public EColorMode ColorMode
        {
            get
            {
                return _ColorMode;
            }
            set
            {
                if (_ColorMode != value)
                {
                    _ColorMode = value;
                    OnPropertyChanged("ColorMode");
                }
            }
        }

        public ExperimentSetting ExperimentSetting
        {
            get
            {
                return _ExperimentSetting;
            }
            set
            {
                _ExperimentSetting = value;
            }
        }

        public int CustomCount
        {
            get
            {
                return _CustomCount;
            }
            private set
            {
                if (_CustomCount != value)
                {
                    _CustomCount = value;
                    OnPropertyChanged("CustomCount");
                }
            }
        }

        public GridColumns GridColumns
        {
            get
            {
                return _GridColumns;
            }
            set
            {
                if (_GridColumns == value)
                {
                    return;
                }
                _GridColumns = value;
                int nowCount = CustomCount;
                List<ColumnInfo> list = (from s in _GridColumns.Columns
                                         where s.IsCustomColumn()
                                         orderby s.FieldIndex
                                         select s).ToList();
                if (list.Count != nowCount)
                {
                    while (nowCount-- > 0)
                    {
                        List<ColumnInfo> list2 = list.Where((ColumnInfo s) => s.FieldIndex == nowCount).ToList();
                        if (list2.Count != 0)
                        {
                            continue;
                        }
                        List<Well> list3 = Wells.Where((Well s) => s.Sample != null).Distinct().ToList();
                        foreach (Well item in list3)
                        {
                            if (nowCount < item.Sample.PatientInfo.CustomData.Count)
                            {
                                item.Sample.PatientInfo.CustomData.RemoveAt(nowCount);
                            }
                        }
                    }
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].FieldIndex = i;
                    }
                }
                int num = list.Count - 1;
                list = _GridColumns.Columns.Where((ColumnInfo s) => s.IsNewCustomColumn()).ToList();
                foreach (ColumnInfo item2 in list)
                {
                    num = (item2.FieldIndex = num + 1);
                    List<Well> list4 = Wells.Where((Well s) => s.Sample != null).Distinct().ToList();
                    foreach (Well item3 in list4)
                    {
                        item3.Sample.PatientInfo.CustomData.Add("");
                    }
                }
                CustomCount = _GridColumns.Columns.Where((ColumnInfo s) => s.AllowDelete).Count();
                OnPropertyChanged("GridColumns");
            }
        }

        public string TempFile { get; set; }

        public DateTime GetInspectionDate()
        {
            return Device.StartTime;
        }

        public Experiment(int count = 96)
        {
            _Device.ModelChangedEvent += _Device_ModelChangedEvent;
            Subsets.CollectionChanged += Subsets_CollectionChanged;
            TempFile = Path.Combine(Utility.GetTempPath(), "temp" + Name + "." + BakExt);
            for (int i = 0; i < count; i++)
            {
                Well well = new Well
                {
                    ColumnIndex = i % 12,
                    RowIndex = i / 12,
                    ID = i,
                    ModelA = (i % 12 < 6)
                };
                well.Event += well_Event;
                _Wells.Add(well);
            }
            InitModelAB();
            _Subsets.Add(new Subset
            {
                IsReadOnly = true,
                Name = "All",
                Wells = _Wells
            });
            CurrentSubset = _Subsets[0];
            Init();
        }

        private void Subsets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action != 0)
            {
                return;
            }
            foreach (Subset newItem in e.NewItems)
            {
                foreach (Well well in newItem.Wells)
                {
                    if (well.Sample == null)
                    {
                        continue;
                    }
                    foreach (SampleTargetItem item in well.Targets)
                    {
                        string key = well.ID.ToString("00") + item.ChannelNo;
                        if (!newItem.CurveParameters.Contains(key))
                        {
                            BasicOptionItem basicOptionItem = newItem.GetSubsetParamter(well.Project).BasicOption.Items.Where((BasicOptionItem s) => s.TubeNo == item.TubeNo && s.ChannelNo == item.ChannelNo).FirstOrDefault();
                            newItem.CurveParameters.Add(key, new Subset.CurveParameter
                            {
                                Use = false,
                                WellNo = well.ID,
                                ChannelNo = item.ChannelNo,
                                BeginBaseline = basicOptionItem.BeginBaseline,
                                EndBaseline = basicOptionItem.EndBaseline,
                                Threshold = basicOptionItem.Threshold
                            });
                        }
                    }
                }
            }
        }

        private void well_Event(object sender, EventArgs e)
        {
            PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
            if (propertyChangedEventArgsEx == null || !(propertyChangedEventArgsEx.PropertyName == "Sample"))
            {
                return;
            }
            Sample sample = propertyChangedEventArgsEx.OldValue as Sample;
            Sample sample2 = propertyChangedEventArgsEx.NewValue as Sample;
            if (sample != null)
            {
                foreach (Well well in sample.Wells)
                {
                    foreach (SampleTargetItem target in well.Targets)
                    {
                        string key = well.ID.ToString("00") + target.ChannelNo;
                        if (BadPoints.ContainsKey(key))
                        {
                            BadPoints.Remove(key);
                        }
                        foreach (Subset subset in Subsets)
                        {
                            subset.CurveParameters.Remove(key);
                        }
                    }
                }
            }
            if (sample2 == null)
            {
                return;
            }
            foreach (Well well2 in sample2.Wells)
            {
                foreach (SampleTargetItem item in well2.Targets)
                {
                    string key2 = well2.ID.ToString("00") + item.ChannelNo;
                    foreach (Subset subset2 in Subsets)
                    {
                        BasicOptionItem basicOptionItem = subset2.GetSubsetParamter(sample2.Project).BasicOption.Items.Where((BasicOptionItem s) => s.TubeNo == item.TubeNo && s.ChannelNo == item.ChannelNo).FirstOrDefault();
                        Subset.CurveParameter curveParameter = new Subset.CurveParameter();
                        curveParameter.Use = false;
                        curveParameter.WellNo = well2.ID;
                        curveParameter.ChannelNo = item.ChannelNo;
                        curveParameter.BeginBaseline = basicOptionItem.BeginBaseline;
                        curveParameter.EndBaseline = basicOptionItem.EndBaseline;
                        curveParameter.Threshold = basicOptionItem.Threshold;
                        Subset.CurveParameter value = curveParameter;
                        if (subset2.CurveParameters.Contains(key2))
                        {
                            subset2.CurveParameters[key2] = value;
                        }
                        else
                        {
                            subset2.CurveParameters.Add(key2, value);
                        }
                    }
                }
            }
        }

        private void Init()
        {
            Program = null;
            foreach (Well well in Wells)
            {
                well.DeleteSmaple();
            }
            MustUseModelA();
            MustUseModelB();
            RefreshGirdColumns();
            ClearResult();
            if (Type == EProjectType.HRM || Type == EProjectType.AD)
            {
                ColorMode = EColorMode.Type;
            }
        }

        private void _Device_RunStateEvent(object sender, EventArgs e)
        {
            if (Status == EExperimentStatus.Completed)
            {
                return;
            }
            switch (_Device.RunState)
            {
                case RunningState.NoRunning:
                    Status = EExperimentStatus.NotRunning;
                    break;
                case RunningState.WaitingInterrupt:
                    Status = EExperimentStatus.Interrupt;
                    break;
                case RunningState.Interrupt:
                    if (_Device.RunError == RunningError.None)
                    {
                        RefreshStatus();
                    }
                    DeleteTemporaryFile();
                    break;
                case RunningState.WaitingRunning:
                case RunningState.Running:
                    Status = EExperimentStatus.Running;
                    break;
                case RunningState.Finish:
                    Status = EExperimentStatus.Completed;
                    break;
            }
        }

        private void _Device_ModelChangedEvent(object sender, EventArgs e)
        {
            if (_Device.Model == Device.DeviceModel_96P || _Device.Model == Device.DeviceModel_96S || _Device.Model == Device.DeviceModel_40P)
            {
                CanUseModelA = true;
                CanUseModelB = true;
            }
            else if (_Device.Model == Device.DeviceModel_48P)
            {
                CanUseModelA = true;
                CanUseModelB = false;
                UseModelA = true;
                UseModelB = false;
            }
            else if (_Device.Model == Device.DeviceModel_24P)
            {
                _CanUseModelA = true;
                _CanUseModelB = false;
                _UseModelA = true;
                _UseModelB = false;
                UpdataSubsetAll();
            }
        }

        private void _Device_SaveTempFileEvent(object sender, EventArgs e)
        {
            SaveTemporaryFile();
        }

        public void ClearResult()
        {
            foreach (Well well in Wells)
            {
                if (well.Sample == null)
                {
                    continue;
                }
                foreach (SampleTargetItem target in well.Targets)
                {
                    target.ResetResult(well.Project.BasicInfo.Type);
                }
                well.ResetResult();
                well.Sample.ResetResult();
            }
            foreach (Project item in CurrentSubset.GetAllProject())
            {
                ProjectStdCurve currentProjectStdCurve = CurrentSubset.GetSubsetParamter(item).CurrentProjectStdCurve;
                currentProjectStdCurve.TargetStdCurveList = null;
            }
        }

        public bool CanTypeChange(EProjectType type)
        {
            switch (type)
            {
                case EProjectType.Melt:
                case EProjectType.HRM:
                    if (_Device.Model == Device.DeviceModel_48P || _Device.Model == Device.DeviceModel_24P)
                    {
                        return true;
                    }
                    if (_CanUseModelA)
                    {
                        return _CanUseModelB;
                    }
                    return false;
                default:
                    return true;
            }
        }

        public bool IsUseAllModel()
        {
            if (_Device.Model == Device.DeviceModel_96S || _Device.Model == Device.DeviceModel_48P || _Device.Model == Device.DeviceModel_24P)
            {
                return true;
            }
            if (_Device.Model == Device.DeviceModel_96P || _Device.Model == Device.DeviceModel_40P)
            {
                if (_UseModelA)
                {
                    return _UseModelB;
                }
                return false;
            }
            return false;
        }

        public void UnLinkProject(bool createNew = true)
        {
            IList<IGrouping<string, Well>> list = (from s in Wells
                                                   where s.Project != null
                                                   group s by s.Project.BasicInfo.Name).ToList();
            foreach (IGrouping<string, Well> item in list)
            {
                Project project = null;
                if (createNew)
                {
                    project = new Project(item.FirstOrDefault().Project);
                    project.PCRProgram = Program;
                }
                foreach (Sample item2 in item.Select((Well s) => s.Sample))
                {
                    if (createNew)
                    {
                        CurrentSubset.UpdateProject(item2.Project, project);
                        item2.Project = project;
                    }
                }
            }
        }

        private void SetDeviceParamter()
        {
            new StringBuilder();
            List<Project> allProject = CurrentSubset.GetAllProject();
            foreach (Project item in allProject)
            {
                if (item.Target.Items.Select((TargetItem s) => s.TubeNo).Distinct().Count() != 1)
                {
                    Rule rule = CurrentSubset.GetSubsetParamter(item).Rule;
                    if (ExecuteCommand.NeedCheckOrder(rule.Data))
                    {
                        Device.IsCheckOrder = true;
                        break;
                    }
                }
            }
            RunVersion = Utility.GetProductFileVersion();
            DumpVersion = Utility.DumpVersion;
            RegisterDeviceRunEvent();
            if (Status == EExperimentStatus.NotRunning || Status == EExperimentStatus.Interrupt)
            {
                _Device.Volume = (from s in Wells
                                  where s.Project != null
                                  select s.Project.BasicInfo.Reaction).Max();
                _Device.UsedBlock = (byte)((UseModelA ? 1 : 0) | (UseModelB ? 2 : 0));
                _Device.HotlidIsHeating = UseHotBonnet;
                _Device.HotlidSetTemperature = (UseHotBonnet ? ConfigSettings.GetInstance().BasicSetting.GetHotlidTemperature(Type) : 0);
                if (TemperatureControlMode == ETemperatureControlMode.Tube)
                {
                    _Device.TemperatureControl = 1;
                }
                else if (TemperatureControlMode == ETemperatureControlMode.Fast)
                {
                    _Device.TemperatureControl = 2;
                }
                else
                {
                    _Device.TemperatureControl = 0;
                }
                _Device.ScanMethod = ((ScanMode == EScanMode.All) ? ((byte)1) : ((byte)0));
                _Device.ScanChannel = 0;
                if (ScanMode == EScanMode.All)
                {
                    for (int i = 0; i < _Device.ChannelNo.Count(); i++)
                    {
                        _Device.ScanChannel |= (byte)((_Device.ChannelNo[i] != 0) ? (1 << i) : 0);
                    }
                }
                else if (ScanMode == EScanMode.Project)
                {
                    List<int> list = new List<int>();
                    List<Project> list2 = (from s in _Wells
                                           where s.Project != null
                                           select s.Project).Distinct().ToList();
                    foreach (Project item2 in list2)
                    {
                        list.AddRange(item2.BasicOption.Items.Select((BasicOptionItem s) => s.ChannelNo).ToList());
                    }
                    list = list.Distinct().ToList();
                    foreach (int item3 in list)
                    {
                        if (_Device.ChannelNo[item3 - 1] != 0)
                        {
                            _Device.ScanChannel |= (byte)(1 << item3 - 1);
                        }
                    }
                }
                else if (ScanMode == EScanMode.None)
                {
                    _Device.ScanChannel = 0;
                }
                _Device.Compensator = ConfigSettings.GetInstance().BasicSetting.Compensator;
                _Device.OpenHotlidDelayTime = ConfigSettings.GetInstance().ExperimentSetting.OpenHotlidDelayTime;
                _Device.CurrentProfile = Program;
            }
            if (File.Exists(LastTempateName))
            {
                File.Delete(LastTempateName);
            }
            SaveTemplate(LastTempateName, false);
        }

        public void ProgramRun()
        {
            _Device.ProgramRun();
        }

        public void Run()
        {
            ClearResult();
            SetDeviceParamter();
            _Device.Run(false);
        }

        public void Continue()
        {
            SetDeviceParamter();
            _Device.Run();
        }

        public void Stop()
        {
            _Device.Interrupt();
        }

        public void RefreshStatus()
        {
            Status = ((!HasEnoughData()) ? EExperimentStatus.Interrupt : EExperimentStatus.Completed);
        }

        public bool CanSave()
        {
            if (Status == EExperimentStatus.Completed)
            {
                return HasEnoughData();
            }
            return false;
        }

        public bool HasOneData()
        {
            return _Device.HasOneData();
        }

        public bool HasEnoughData()
        {
            return _Device.HasEnoughData();
        }

        public bool HasData()
        {
            return _Device.HasData();
        }

        public bool CanAddOrDeleteSegment()
        {
            if (Status == EExperimentStatus.Running && !string.IsNullOrEmpty(GetCurrentSegment()))
            {
                return !Device.RunningSegIsMelting;
            }
            return false;
        }

        public string GetCurrentSegment()
        {
            return Device.GetCurrentSegmentName();
        }

        public int GetCurrentSegmentCycle()
        {
            return Device.Cycles;
        }

        public bool RemoveCurrentSegment(string name)
        {
            if (Device.RemoveCurrentSegment(name))
            {
                ProgramChannged();
                return true;
            }
            return false;
        }

        public bool AddCurrentSegmentCycles(string name, int cycle)
        {
            if (Device.AddCurrentSegmentCycles(name, cycle))
            {
                ProgramChannged();
                return true;
            }
            return false;
        }

        private void ProgramChannged()
        {
            PCRProgram program = Program;
            Program = null;
            Program = program;
        }

        public int WellIndex(Well well)
        {
            return Wells.IndexOf(well);
        }

        public bool Save(string path, bool saveTemp = false)
        {
            if (!saveTemp && !CanSave())
            {
                return false;
            }
            Utility.CreateFolder(Path.GetDirectoryName(path));
            bool flag = false;
            FileStream fileStream = null;
            StreamEx streamEx = new StreamEx();
            try
            {
                SaveToStream(streamEx);
                streamEx.Seek(0L, SeekOrigin.Begin);
                fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
                streamEx.CopyTo(fileStream);
                flag = true;
            }
            catch (Exception)
            {
            }
            finally
            {
                if (streamEx != null)
                {
                    streamEx.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (!saveTemp)
                {
                    DeleteTemporaryFile();
                }
            }
            if (flag && !saveTemp)
            {
                ConfigSettings.GetInstance().History.AddExperimentHistory(path);
                DefaultPath = Path.GetDirectoryName(path);
                Name = Path.GetFileNameWithoutExtension(path);
            }
            return flag;
        }

        public bool SaveTemplate(string path, bool addHistoty = true, EPatientInfoSaveType savePatientInfo = EPatientInfoSaveType.None)
        {
            try
            {
                FileStream fileStream = null;
                StreamEx streamEx = new StreamEx();
                try
                {
                    fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
                    SaveTemplateToStream(streamEx, savePatientInfo);
                    streamEx.Seek(0L, SeekOrigin.Begin);
                    streamEx.CopyTo(fileStream);
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    if (streamEx != null)
                    {
                        streamEx.Close();
                    }
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }
                if (addHistoty)
                {
                    ConfigSettings.GetInstance().History.AddExperimentTemplateHistory(path);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public Experiment CloneTemplate(Experiment experiment, EPatientInfoSaveType savePatientInfo = EPatientInfoSaveType.None)
        {
            Experiment result = null;
            try
            {
                StreamEx streamEx = new StreamEx();
                Experiment experiment2 = new Experiment();
                SaveTemplateToStream(streamEx, savePatientInfo);
                streamEx.Seek(0L, SeekOrigin.Begin);
                if (experiment2.ReadFromStream(streamEx))
                {
                    result = experiment2;
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        public static Experiment Load(string path, bool addHistory = true)
        {
            Experiment experiment = null;
            FileStream fileStream = null;
            StreamEx streamEx = new StreamEx();
            try
            {
                Experiment experiment2 = new Experiment();
                fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                fileStream.CopyTo(streamEx);
                streamEx.Seek(0L, SeekOrigin.Begin);
                if (experiment2.ReadFromStream(streamEx))
                {
                    experiment = experiment2;
                }
            }
            catch (Exception ex)
            {
                Log.Debug(string.Format("Load Experiment Error:{0}", ex.Message));
            }
            finally
            {
                if (streamEx != null)
                {
                    streamEx.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
            if (experiment == null)
            {
                experiment = ReadOldPcr.Read(path);
                if (experiment == null)
                {
                    return null;
                }
            }
            if (addHistory)
            {
                ConfigSettings.GetInstance().History.AddExperimentHistory(path);
            }
            experiment.RegisterDeviceRunEvent();
            experiment.Name = Path.GetFileNameWithoutExtension(path);
            experiment.DefaultPath = Path.GetDirectoryName(path);
            return experiment;
        }

        public static Experiment LoadTemplate(string path, bool saveHistory = true)
        {
            if (!File.Exists(path))
            {
                return null;
            }
            Experiment experiment = new Experiment();
            try
            {
                FileStream fileStream = null;
                StreamEx streamEx = new StreamEx();
                try
                {
                    Experiment experiment2 = new Experiment();
                    fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                    fileStream.CopyTo(streamEx);
                    streamEx.Seek(0L, SeekOrigin.Begin);
                    if (experiment2.ReadFromStream(streamEx))
                    {
                        experiment = experiment2;
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (streamEx != null)
                    {
                        streamEx.Close();
                    }
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }
                experiment.UpdataSubsetAll();
                if (saveHistory)
                {
                    ConfigSettings.GetInstance().History.AddExperimentTemplateHistory(path);
                }
                return experiment;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static Experiment LoadExperimentFromCsv(string path)
        {
            List<string> list = File.ReadAllLines(path, Utility.GetFileEncoding(path)).ToList();
            for (int num = list.Count() - 1; num >= 0; num--)
            {
                if (list[num].StartsWith("//"))
                {
                    list.RemoveAt(num);
                }
            }
            int num2 = list.IndexOf("[WELLPLATE]");
            StringBuilder stringBuilder = new StringBuilder();
            if (num2 != -1)
            {
                for (int i = 0; i < num2; i++)
                {
                    stringBuilder.AppendLine(list[i]);
                }
                list.RemoveRange(0, num2 + 1);
            }
            if (list.Count() < 2)
            {
                MessageBox.Show("文件数据至少有一条数据。");
                return null;
            }
            List<string> list2 = new List<string>(list[0].Split(','));
            List<List<string>> dates = new List<List<string>>();
            for (int j = 1; j < list.Count(); j++)
            {
                dates.Add(new List<string>(list[j].Split(',')));
            }
            int wellNoIndex = list2.IndexOf("WellNo");
            int prjIndex = list2.IndexOf("TestPrj");
            int num3 = list2.IndexOf("TubeNo");
            if (wellNoIndex == -1 || prjIndex == -1)
            {
                MessageBox.Show("文件格式不正确。");
                return null;
            }
            List<string> projectNames = new List<string>();
            for (int k = 0; k < dates.Count(); k++)
            {
                if (!projectNames.Contains(dates[k][prjIndex]))
                {
                    projectNames.Add(dates[k][prjIndex]);
                }
            }
            int l;
            for (l = projectNames.Count - 1; l >= 0; l--)
            {
                if (ProjectManage.GetInstance().AllProjectList.Where((Project s) => s.BasicInfo.Name == projectNames[l]).Count() > 0)
                {
                    projectNames.RemoveAt(l);
                }
            }
            if (projectNames.Count > 0)
            {
                StringBuilder stringBuilder2 = new StringBuilder();
                stringBuilder2.AppendLine("本地不存在以下项目：");
                foreach (string item in projectNames)
                {
                    stringBuilder2.AppendLine(item);
                }
                MessageBox.Show(stringBuilder2.ToString());
                return null;
            }
            Experiment experiment = new Experiment();
            experiment.PreTreatment = stringBuilder.ToString();
            StringBuilder stringBuilder3 = new StringBuilder();
            foreach (string item2 in list)
            {
                stringBuilder3.AppendLine(item2);
            }
            experiment._CSVContent = stringBuilder3.ToString();
            Sample sample = null;
            Project project = null;
            List<ColumnInfo> list3 = null;
            int m;
            for (m = 0; m < dates.Count; m++)
            {
                Well well = experiment.Wells.Where((Well s) => s.CellName == dates[m][wellNoIndex]).FirstOrDefault();
                if (well == null)
                {
                    continue;
                }
                if (project == null || project.BasicInfo.Name != dates[m][prjIndex])
                {
                    project = new Project(ProjectManage.GetInstance().AllProjectList.Where((Project s) => s.BasicInfo.Name == dates[m][prjIndex]).FirstOrDefault());
                }
                if (m == 0)
                {
                    experiment.Type = project.BasicInfo.Type;
                    experiment.Program = new PCRProgram(project.PCRProgram);
                    GridColumns gridColumns = new GridColumns();
                    gridColumns.Columns = new ObservableCollection<ColumnInfo>(experiment.GridColumns.Columns);
                    GridColumns gridColumns2 = gridColumns;
                    foreach (string item3 in list2)
                    {
                        if (!(item3 != "WellNo") || !(item3 != "TestPrj") || !(item3 != "TubeNo") || !(item3 != "Type") || !(item3 != "Property") || !(item3 != "ReTubeNo") || !(item3 != "Barcode") || !(item3 != "PName") || !(item3 != "PID") || !(item3 != "PSex") || !(item3 != "PAge") || !(item3 != "PSpecimen") || !(item3 != "PSpecimenDate") || !(item3 != "PDoctor") || !(item3 != "POffice") || !(item3 != "PDiagnosis") || !(item3 != "PCaseID") || !(item3 != "PBedID") || !(item3 != "PInPatientID") || !(item3 != "POutPatientID") || !(item3 != "PRemark") || !(item3 != "SName"))
                        {
                            continue;
                        }
                        string[] array = item3.Split('|');
                        if (array.Count() > 0)
                        {
                            string content = array[0];
                            if (!string.IsNullOrEmpty(content) && gridColumns2.Columns.Where((ColumnInfo s) => s.AllowDelete && s.Header == content).Count() == 0)
                            {
                                ColumnInfo columnInfo = new ColumnInfo();
                                columnInfo.Header = content;
                                gridColumns2.Columns.Add(columnInfo);
                            }
                        }
                    }
                    experiment.GridColumns = gridColumns2;
                }
                bool flag = true;
                int tubeNo = 1;
                if (num3 != -1)
                {
                    int.TryParse(dates[m][num3], out tubeNo);
                    if (tubeNo > 1)
                    {
                        flag = false;
                    }
                    else
                    {
                        tubeNo = 1;
                    }
                }
                if (flag)
                {
                    sample = new Sample(project, experiment.CustomCount);
                }
                sample.Wells.Add(well);
                well.SetSample(sample, tubeNo);
                if (list3 == null)
                {
                    list3 = experiment.GridColumns.Columns.Where((ColumnInfo s) => s.AllowDelete).ToList();
                }
                for (int n = 0; n < Math.Min(list2.Count, dates[m].Count); n++)
                {
                    List<SampleTargetItem> list4 = sample.Items.Where((SampleTargetItem s) => s.TubeNo == tubeNo).ToList();
                    foreach (SampleTargetItem item4 in list4)
                    {
                        switch (list2[n])
                        {
                            case "Type":
                                switch (dates[m][n])
                                {
                                    case "0":
                                        item4.SampleType = SampleType.Unknown;
                                        break;
                                    case "1":
                                        item4.SampleType = SampleType.Standard;
                                        break;
                                    case "2":
                                        item4.SampleType = SampleType.HighPositive;
                                        break;
                                    case "3":
                                        item4.SampleType = SampleType.LowPositive;
                                        break;
                                    case "4":
                                        item4.SampleType = SampleType.Negative;
                                        break;
                                    case "5":
                                        item4.SampleType = SampleType.NTC;
                                        break;
                                    case "6":
                                        item4.SampleType = SampleType.QC;
                                        break;
                                    case "7":
                                        item4.SampleType = SampleType.RetestSample;
                                        break;
                                    default:
                                        item4.SampleType = SampleType.Unknown;
                                        break;
                                }
                                continue;
                            case "Property":
                                item4.Property = dates[m][n];
                                continue;
                            case "ReTubeNo":
                                sample.CompoundTubeNo = dates[m][n];
                                continue;
                            case "SName":
                                sample.SampleName = dates[m][n];
                                continue;
                            case "Barcode":
                            case "PID":
                                sample.PatientInfo.ID = dates[m][n];
                                continue;
                            case "PName":
                                sample.PatientInfo.Name = dates[m][n];
                                continue;
                            case "PSex":
                                sample.PatientInfo.Sex = dates[m][n];
                                continue;
                            case "PAge":
                                sample.PatientInfo.Age = dates[m][n];
                                continue;
                            case "PSpecimen":
                                sample.PatientInfo.Specimen = dates[m][n];
                                continue;
                            case "PSpecimenDate":
                                sample.PatientInfo.SpecimenDate = dates[m][n];
                                continue;
                            case "PDoctor":
                                sample.PatientInfo.Doctor = dates[m][n];
                                continue;
                            case "POffice":
                                sample.PatientInfo.Office = dates[m][n];
                                continue;
                            case "PDiagnosis":
                                sample.PatientInfo.Diagnosis = dates[m][n];
                                continue;
                            case "PCaseID":
                                sample.PatientInfo.CaseID = dates[m][n];
                                continue;
                            case "PBedID":
                                sample.PatientInfo.BedID = dates[m][n];
                                continue;
                            case "PInPatientID":
                                sample.PatientInfo.InPatientID = dates[m][n];
                                continue;
                            case "POutPatientID":
                                sample.PatientInfo.OutPatientID = dates[m][n];
                                continue;
                            case "PRemark":
                                sample.PatientInfo.Remark = dates[m][n];
                                continue;
                            case "WellNo":
                            case "TestPrj":
                            case "TubeNo":
                                continue;
                        }
                        string[] array2 = list2[n].Split('|');
                        if (array2.Count() <= 0)
                        {
                            continue;
                        }
                        string content2 = array2[0];
                        ColumnInfo columnInfo2 = list3.Where((ColumnInfo s) => s.Header == content2).FirstOrDefault();
                        if (columnInfo2 != null)
                        {
                            int num4 = list3.IndexOf(columnInfo2);
                            if (sample.PatientInfo.CustomData.Count > num4)
                            {
                                sample.PatientInfo.CustomData[num4] = dates[m][n];
                            }
                        }
                    }
                }
            }
            return experiment;
        }

        public void SaveTemporaryFile()
        {
            Save(TempFile, true);
        }

        public void DeleteTemporaryFile()
        {
            try
            {
                if (File.Exists(TempFile))
                {
                    File.Copy(TempFile, Path.Combine(Utility.GetBakPath(), Path.GetFileName(TempFile)), true);
                    File.Delete(TempFile);
                }
            }
            catch
            {
            }
        }

        private void SaveTemplateToStream(StreamEx stream, EPatientInfoSaveType savePatientInfo = EPatientInfoSaveType.None)
        {
            stream.Write(PropertyKey.Key_Experiment);
            List<PropertyKey> list = new List<PropertyKey>();
            List<byte[]> list2 = new List<byte[]>();
            list.Add(PropertyKey.Key_Version);
            list2.Add(BytesConverter.GetBytes(Utility.GetProductFileVersion()));
            list.Add(PropertyKey.Key_Type);
            list2.Add(BytesConverter.GetBytes((int)Type));
            list.Add(PropertyKey.Key_UseModelA);
            list2.Add(BytesConverter.GetBytes(UseModelA));
            list.Add(PropertyKey.Key_UseModelB);
            list2.Add(BytesConverter.GetBytes(UseModelB));
            list.Add(PropertyKey.Key_UseHotBonnet);
            list2.Add(BytesConverter.GetBytes(UseHotBonnet));
            list.Add(PropertyKey.Key_TemperatureControlMode);
            list2.Add(BytesConverter.GetBytes((int)TemperatureControlMode));
            list.Add(PropertyKey.Key_ScanMode);
            list2.Add(BytesConverter.GetBytes((int)ScanMode));
            list.Add(PropertyKey.Key_SimpleName);
            list2.Add(BytesConverter.GetBytes(Simple_Name));
            list.Add(PropertyKey.Key_TemplateRemarks);
            list2.Add(BytesConverter.GetBytes(TemplateRemarks));
            if (Image != null)
            {
                list.Add(PropertyKey.Key_Image);
                list2.Add(Image);
            }
            StreamEx streamEx;
            if (Program != null)
            {
                list.Add(PropertyKey.Key_Program);
                streamEx = new StreamEx();
                Program.SaveToStream(streamEx);
                list2.Add(streamEx.ToArray());
                streamEx.Close();
            }
            list.Add(PropertyKey.Key_Wells);
            streamEx = new StreamEx();
            SaveToStreamWells(Wells, streamEx, false, savePatientInfo);
            list2.Add(streamEx.ToArray());
            streamEx.Close();
            stream.Write(PropertyKey.Key_Index);
            stream.WriteIndex(list, list2);
            stream.Flush();
        }

        public ExperimentTemporary GetExperimentTemporaryInfo()
        {
            ExperimentTemporary experimentTemporary = new ExperimentTemporary();
            experimentTemporary.Type = Type;
            experimentTemporary.Status = Status;
            experimentTemporary.BreakPoint = Device.BreakPoint;
            return experimentTemporary;
        }

        public void SaveToStream(StreamEx stream)
        {
            StreamEx streamEx = null;
            stream.Write(PropertyKey.Key_Experiment);
            ExperimentTemporary experimentTemporaryInfo = GetExperimentTemporaryInfo();
            experimentTemporaryInfo.SaveToStream(stream);
            List<PropertyKey> list = new List<PropertyKey>();
            List<byte[]> list2 = new List<byte[]>();
            if (!string.IsNullOrEmpty(RunVersion))
            {
                list.Add(PropertyKey.Key_VersionCreate);
                list2.Add(BytesConverter.GetBytes(RunVersion));
            }
            if (!string.IsNullOrEmpty(DumpVersion))
            {
                list.Add(PropertyKey.Key_VersionDump);
                list2.Add(BytesConverter.GetBytes(DumpVersion));
            }
            list.Add(PropertyKey.Key_Version);
            list2.Add(BytesConverter.GetBytes(Utility.GetProductFileVersion()));
            if (!string.IsNullOrEmpty(TempFile))
            {
                list.Add(PropertyKey.Key_TempFile);
                list2.Add(BytesConverter.GetBytes(TempFile));
            }
            if (!string.IsNullOrEmpty(PreTreatment))
            {
                list.Add(PropertyKey.Key_PreTreatment);
                list2.Add(BytesConverter.GetBytes(PreTreatment));
            }
            list.Add(PropertyKey.Key_Status);
            list2.Add(BytesConverter.GetBytes((int)Status));
            if (!string.IsNullOrEmpty(Password))
            {
                list.Add(PropertyKey.Key_Password);
                list2.Add(BytesConverter.GetBytes(Password));
            }
            list.Add(PropertyKey.Key_Type);
            list2.Add(BytesConverter.GetBytes((int)Type));
            if (!string.IsNullOrEmpty(Name))
            {
                list.Add(PropertyKey.Key_Name);
                list2.Add(BytesConverter.GetBytes(Name));
            }
            if (!string.IsNullOrEmpty(Operator))
            {
                list.Add(PropertyKey.Key_Operator);
                list2.Add(BytesConverter.GetBytes(Operator));
            }
            if (!string.IsNullOrEmpty(Operator2))
            {
                list.Add(PropertyKey.Key_Operator2);
                list2.Add(BytesConverter.GetBytes(Operator2));
            }
            if (!string.IsNullOrEmpty(Auditor))
            {
                list.Add(PropertyKey.Key_Auditor);
                list2.Add(BytesConverter.GetBytes(Auditor));
            }
            if (!string.IsNullOrEmpty(Note))
            {
                list.Add(PropertyKey.Key_Note);
                list2.Add(BytesConverter.GetBytes(Note));
            }
            list.Add(PropertyKey.Key_UseModelA);
            list2.Add(BytesConverter.GetBytes(UseModelA));
            list.Add(PropertyKey.Key_UseModelB);
            list2.Add(BytesConverter.GetBytes(UseModelB));
            list.Add(PropertyKey.Key_UseHotBonnet);
            list2.Add(BytesConverter.GetBytes(UseHotBonnet));
            list.Add(PropertyKey.Key_TemperatureControlMode);
            list2.Add(BytesConverter.GetBytes((int)TemperatureControlMode));
            list.Add(PropertyKey.Key_ScanMode);
            list2.Add(BytesConverter.GetBytes((int)ScanMode));
            if (!string.IsNullOrEmpty(CSVContent))
            {
                list.Add(PropertyKey.Key_CSVContent);
                list2.Add(BytesConverter.GetBytes(CSVContent));
            }
            list.Add(PropertyKey.Key_ColorMode);
            list2.Add(BytesConverter.GetBytes((int)ColorMode));
            list.Add(PropertyKey.Key_ExperimentSetting);
            streamEx = new StreamEx();
            ExperimentSetting.SaveToStream(streamEx);
            list2.Add(streamEx.ToArray());
            streamEx.Close();
            list.Add(PropertyKey.Key_Columns);
            streamEx = new StreamEx();
            GridColumns.SaveToStream(streamEx);
            list2.Add(streamEx.ToArray());
            streamEx.Close();
            if (Program != null)
            {
                list.Add(PropertyKey.Key_Program);
                streamEx = new StreamEx();
                Program.SaveToStream(streamEx);
                list2.Add(streamEx.ToArray());
                streamEx.Close();
            }
            list.Add(PropertyKey.Key_Wells);
            streamEx = new StreamEx();
            SaveToStreamWells(Wells, streamEx, false, EPatientInfoSaveType.All);
            list2.Add(streamEx.ToArray());
            streamEx.Close();
            list.Add(PropertyKey.Key_Subsets);
            streamEx = new StreamEx();
            streamEx.Write(Subsets.Count);
            foreach (Subset subset in Subsets)
            {
                subset.SaveToStream(streamEx, Wells);
            }
            list2.Add(streamEx.ToArray());
            streamEx.Close();
            list.Add(PropertyKey.Key_Device);
            list2.Add(Device.SaveDevice().ToArray());
            if (BadPoints.Count > 0)
            {
                list.Add(PropertyKey.Key_BadPoints);
                streamEx = new StreamEx();
                streamEx.Write(BadPoints.Count);
                foreach (BadPoint value in BadPoints.Values)
                {
                    value.SaveToStream(streamEx);
                }
                list2.Add(streamEx.ToArray());
                streamEx.Close();
            }
            list.Add(PropertyKey.Key_MarkBadPoint);
            list2.Add(BytesConverter.GetBytes(MarkBadPoint));
            stream.Write(PropertyKey.Key_Index);
            stream.WriteIndex(list, list2);
            stream.Flush();
        }

        public static ExperimentTemporary GetExperimentTemporaryInfo(string file)
        {
            ExperimentTemporary experimentTemporary = new ExperimentTemporary();
            if (!File.Exists(file))
            {
                return experimentTemporary;
            }
            try
            {
                using (FileStream fileStream = File.OpenRead(file))
                {
                    StreamEx streamEx = new StreamEx();
                    fileStream.CopyTo(streamEx, 100);
                    streamEx.Seek(0L, SeekOrigin.Begin);
                    PropertyKey propertyKey = streamEx.ReadKey();
                    if (propertyKey == PropertyKey.Key_Version)
                    {
                        streamEx.ReadString();
                        propertyKey = streamEx.ReadKey();
                    }
                    if (propertyKey == PropertyKey.Key_Experiment)
                    {
                        experimentTemporary.ReadFromStream(streamEx);
                    }
                    streamEx.Close();
                }
                if (experimentTemporary != null && experimentTemporary.Type == EProjectType.All)
                {
                    Experiment experiment = Load(file, false);
                    if (experiment != null)
                    {
                        experimentTemporary.Type = experiment.Type;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex.Message);
            }
            return experimentTemporary;
        }

        public bool ReadFromStream(StreamEx stream)
        {
            PropertyKey propertyKey = stream.ReadKey();
            if (propertyKey == PropertyKey.Key_Version)
            {
                string updateVersion = stream.ReadString();
                UpdateVersion = updateVersion;
                propertyKey = stream.ReadKey();
            }
            else
            {
                UpdateVersion = string.Empty;
            }
            if (propertyKey != PropertyKey.Key_Experiment)
            {
                return false;
            }
            new ExperimentTemporary().ReadFromStream(stream);
            propertyKey = stream.ReadKey();
            if (propertyKey == PropertyKey.Key_Index)
            {
                List<PropertyKey> keys;
                List<byte[]> dates;
                stream.ReadIndex(out keys, out dates);
                for (int i = 0; i < keys.Count; i++)
                {
                    switch (keys[i])
                    {
                        case PropertyKey.Key_Version:
                            UpdateVersion = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_VersionDump:
                            DumpVersion = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_VersionCreate:
                            RunVersion = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_TempFile:
                            TempFile = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Password:
                            Password = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Type:
                            Type = (EProjectType)BytesConverter.BytesToInt(dates[i]);
                            break;
                        case PropertyKey.Key_Name:
                            Name = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Operator:
                            Operator = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Operator2:
                            Operator2 = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Auditor:
                            Auditor = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Note:
                            Note = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_UseModelA:
                            UseModelA = BytesConverter.BytesToBool(dates[i]);
                            break;
                        case PropertyKey.Key_UseModelB:
                            UseModelB = BytesConverter.BytesToBool(dates[i]);
                            break;
                        case PropertyKey.Key_UseHotBonnet:
                            UseHotBonnet = BytesConverter.BytesToBool(dates[i]);
                            break;
                        case PropertyKey.Key_TemperatureControlMode:
                            TemperatureControlMode = (ETemperatureControlMode)BytesConverter.BytesToInt(dates[i]);
                            break;
                        case PropertyKey.Key_ScanMode:
                            ScanMode = (EScanMode)BytesConverter.BytesToInt(dates[i]);
                            break;
                        case PropertyKey.Key_CSVContent:
                            CSVContent = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_PreTreatment:
                            PreTreatment = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Status:
                            Status = (EExperimentStatus)BytesConverter.BytesToInt(dates[i]);
                            break;
                        case PropertyKey.Key_ColorMode:
                            ColorMode = (EColorMode)BytesConverter.BytesToInt(dates[i]);
                            break;
                        case PropertyKey.Key_SimpleName:
                            Simple_Name = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_TemplateRemarks:
                            TemplateRemarks = BytesConverter.BytesToString(dates[i]);
                            break;
                        case PropertyKey.Key_Image:
                            Image = dates[i];
                            break;
                        case PropertyKey.Key_Program:
                            {
                                Program = new PCRProgram();
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                Program.ReadFromStream(streamEx);
                                streamEx.Close();
                                Device.CurrentProfile = Program;
                                break;
                            }
                        case PropertyKey.Key_Wells:
                            {
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                ReadFromStreamWells(Wells, streamEx, CustomCount);
                                streamEx.Close();
                                break;
                            }
                        case PropertyKey.Key_Subsets:
                            {
                                Subsets.Clear();
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                int num = streamEx.ReadInt();
                                for (int k = 0; k < num; k++)
                                {
                                    Subset subset = new Subset();
                                    subset.ReadFromStream(streamEx, Wells);
                                    Subsets.Add(subset);
                                }
                                CurrentSubset = Subsets[0];
                                streamEx.Close();
                                break;
                            }
                        case PropertyKey.Key_Device:
                            Device.LoadDevice(dates[i]);
                            break;
                        case PropertyKey.Key_ExperimentSetting:
                            {
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                ExperimentSetting.ReadFromStream(streamEx);
                                streamEx.Close();
                                break;
                            }
                        case PropertyKey.Key_Columns:
                            {
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                GridColumns gridColumns = ColumnsFactory.CreateColumns(Type);
                                gridColumns.ReadFromStream(streamEx);
                                streamEx.Close();
                                GridColumns = gridColumns;
                                break;
                            }
                        case PropertyKey.Key_BadPoints:
                            {
                                StreamEx streamEx = new StreamEx();
                                streamEx.Write(dates[i]);
                                streamEx.Seek(0L, SeekOrigin.Begin);
                                int num = streamEx.ReadInt();
                                BadPoints.Clear();
                                for (int j = 0; j < num; j++)
                                {
                                    BadPoint badPoint = new BadPoint();
                                    badPoint.ReadFromStream(streamEx);
                                    BadPoints.Add(badPoint.WellNo.ToString("00") + badPoint.ChannelNo, badPoint);
                                }
                                streamEx.Close();
                                break;
                            }
                        case PropertyKey.Key_MarkBadPoint:
                            MarkBadPoint = BytesConverter.BytesToBool(dates[i]);
                            break;
                    }
                }
                return true;
            }
            stream.Seek(-4L, SeekOrigin.Current);
            while (true)
            {
                switch (stream.ReadKey())
                {
                    case PropertyKey.Key_ExperimentTemporaryInfo:
                        {
                            int num2 = stream.ReadInt();
                            stream.ReadBytes(num2);
                            break;
                        }
                    case PropertyKey.Key_Password:
                        Password = stream.ReadString();
                        break;
                    case PropertyKey.Key_Type:
                        Type = (EProjectType)stream.ReadInt();
                        break;
                    case PropertyKey.Key_Name:
                        Name = stream.ReadString();
                        break;
                    case PropertyKey.Key_Operator:
                        Operator = stream.ReadString();
                        break;
                    case PropertyKey.Key_Auditor:
                        Auditor = stream.ReadString();
                        break;
                    case PropertyKey.Key_Note:
                        Note = stream.ReadString();
                        break;
                    case PropertyKey.Key_UseModelA:
                        UseModelA = stream.ReadBool();
                        break;
                    case PropertyKey.Key_UseModelB:
                        UseModelB = stream.ReadBool();
                        break;
                    case PropertyKey.Key_UseHotBonnet:
                        UseHotBonnet = stream.ReadBool();
                        break;
                    case PropertyKey.Key_TemperatureControlMode:
                        TemperatureControlMode = (ETemperatureControlMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_ScanMode:
                        ScanMode = (EScanMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_Status:
                        Status = (EExperimentStatus)stream.ReadInt();
                        break;
                    case PropertyKey.Key_TubeSortByColumn:
                        stream.ReadBool();
                        break;
                    case PropertyKey.Key_ColorMode:
                        ColorMode = (EColorMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_Program:
                        Program = new PCRProgram();
                        Program.ReadFromStream(stream);
                        break;
                    case PropertyKey.Key_Wells:
                        ReadFromStreamWells(Wells, stream, CustomCount);
                        if (Program == null)
                        {
                            Program = (from s in Wells
                                       where s.Project != null
                                       select s.Project.PCRProgram).FirstOrDefault();
                        }
                        break;
                    case PropertyKey.Key_StandardCurveSelector:
                        {
                            StandardCurveManage standardCurveManage = new StandardCurveManage();
                            standardCurveManage.ReadFromStream(stream);
                            break;
                        }
                    case PropertyKey.Key_Subsets:
                        {
                            Subsets.Clear();
                            int num2 = stream.ReadInt();
                            for (int m = 0; m < num2; m++)
                            {
                                Subset subset2 = new Subset();
                                subset2.ReadFromStream(stream, Wells);
                                Subsets.Add(subset2);
                            }
                            CurrentSubset = Subsets[0];
                            break;
                        }
                    case PropertyKey.Key_Device:
                        {
                            int num2 = stream.ReadInt();
                            byte[] buffer = new byte[num2];
                            stream.Read(buffer, 0, num2);
                            Device.LoadDevice(buffer);
                            Device.CurrentProfile = Program;
                            break;
                        }
                    case PropertyKey.Key_ExperimentSetting:
                        ExperimentSetting.ReadFromStream(stream);
                        break;
                    case PropertyKey.Key_Columns:
                        GridColumns.ReadFromStream(stream);
                        break;
                    case PropertyKey.Key_CustomImportName:
                        ExperimentSetting.AMPCurveDisplayThreshold = stream.ReadBool();
                        break;
                    case PropertyKey.Key_AutoSaveOption:
                        ExperimentSetting.StandardCurverDisplayAll = stream.ReadBool();
                        break;
                    case PropertyKey.Key_CurverWidth:
                        ExperimentSetting.CurverWidth = (ESizeMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_HighLight:
                        ExperimentSetting.HighLight = stream.ReadBool();
                        break;
                    case PropertyKey.Key_WellHighLight:
                        stream.ReadBool();
                        break;
                    case PropertyKey.Key_InfoHighLight:
                        stream.ReadBool();
                        break;
                    case PropertyKey.Key_CurveHighLight:
                        stream.ReadBool();
                        break;
                    case PropertyKey.Key_WellSelectMode:
                        ExperimentSetting.WellSelectMode = (EWellSelectMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_PressCtlCanSelectWell:
                        ExperimentSetting.PressCtlCanSelectWell = stream.ReadBool();
                        break;
                    case PropertyKey.Key_ChannelSelectMode:
                        ExperimentSetting.ChannelSelectMode = (EChannelSelectMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_UseSubset:
                        ExperimentSetting.UseSubset = stream.ReadBool();
                        break;
                    case PropertyKey.Key_AMPAlgorithm:
                        ExperimentSetting.AMPAlgorithm = (EAMPAlgorithm)stream.ReadInt();
                        break;
                    case PropertyKey.Key_Use:
                        ExperimentSetting.SampleSortMode = (ESampleSortMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_WellNo:
                        ExperimentSetting.DataRowSelectMode = (EDataRowSelectMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_RowSpaceMode:
                        ExperimentSetting.RowSpaceMode = (ERowSpaceMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_CurveParameters:
                        ExperimentSetting.ParamterVisible = stream.ReadBool();
                        break;
                    case PropertyKey.Key_CurveParameter:
                        ExperimentSetting.WellPlateVisible = stream.ReadBool();
                        break;
                    case PropertyKey.Key_ShowCurveToolTips:
                        ExperimentSetting.ShowCurveToolTips = stream.ReadBool();
                        break;
                    case PropertyKey.Key_FileExt:
                        ExperimentSetting.CurveMaxYMode = (ECurveMaxYMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_TableSizeMode:
                        ExperimentSetting.TableSizeMode = (ESizeMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_UseScientific:
                        ExperimentSetting.UseScientific = stream.ReadBool();
                        break;
                    case PropertyKey.Key_ShowPeak:
                        ExperimentSetting.ShowPeak = stream.ReadBool();
                        break;
                    case PropertyKey.Key_WellDisplayMode:
                        ExperimentSetting.WellDisplayMode = (EWellDisplayMode)stream.ReadInt();
                        break;
                    case PropertyKey.Key_Patient:
                        {
                            GridColumns gridColumns2 = new GridColumns();
                            gridColumns2.ReadFromStream(stream);
                            break;
                        }
                    case PropertyKey.Key_NotDisplayNullColumn:
                        stream.ReadBool();
                        break;
                    case PropertyKey.Key_ColumnsVisible:
                        {
                            int num2 = stream.ReadInt();
                            for (int l = 0; l < num2; l++)
                            {
                                stream.ReadString();
                                stream.ReadBool();
                            }
                            break;
                        }
                    default:
                        stream.Seek(-4L, SeekOrigin.Current);
                        return true;
                }
            }
        }

        public static void SaveToStreamWells(List<Well> wells, StreamEx stream, bool saveRawCurve = false, EPatientInfoSaveType savePatientInfo = EPatientInfoSaveType.None)
        {
            List<Sample> list = (from s in wells
                                 where s.Sample != null
                                 select s.Sample).Distinct().ToList();
            List<Project> list2 = list.Select((Sample s) => s.Project).Distinct().ToList();
            List<PropertyKey> list3 = new List<PropertyKey>();
            List<byte[]> list4 = new List<byte[]>();
            StreamEx streamEx = null;
            list3.Add(PropertyKey.Key_Project);
            streamEx = new StreamEx();
            streamEx.Write(list2.Count);
            foreach (Project item in list2)
            {
                item.SaveToStream(streamEx);
            }
            list4.Add(streamEx.ToArray());
            streamEx.Close();
            list3.Add(PropertyKey.Key_Sample);
            streamEx = new StreamEx();
            streamEx.Write(list.Count);
            foreach (Sample item2 in list)
            {
                streamEx.Write(list2.IndexOf(item2.Project));
                item2.SaveToStream(streamEx, saveRawCurve, savePatientInfo);
            }
            list4.Add(streamEx.ToArray());
            streamEx.Close();
            list3.Add(PropertyKey.Key_Wells);
            streamEx = new StreamEx();
            streamEx.Write(list.Select((Sample s) => s.Wells.Count).Sum());
            for (int i = 0; i < list.Count; i++)
            {
                foreach (Well well in list[i].Wells)
                {
                    streamEx.Write(wells.IndexOf(well));
                    streamEx.Write(i);
                    well.SaveToStream(streamEx);
                }
            }
            list4.Add(streamEx.ToArray());
            streamEx.Close();
            stream.Write(PropertyKey.Key_Wells);
            stream.Write(PropertyKey.Key_Index);
            stream.WriteIndex(list3, list4);
            stream.Flush();
        }

        public static bool ReadFromStreamWells(List<Well> wells, StreamEx stream, int customCount = 0)
        {
            List<Sample> list = new List<Sample>();
            List<Project> list2 = new List<Project>();
            PropertyKey propertyKey = stream.ReadKey();
            StreamEx streamEx = null;
            if (propertyKey == PropertyKey.Key_Wells)
            {
                propertyKey = stream.ReadKey();
                if (propertyKey == PropertyKey.Key_Index)
                {
                    List<PropertyKey> keys;
                    List<byte[]> dates;
                    stream.ReadIndex(out keys, out dates);
                    for (int i = 0; i < keys.Count; i++)
                    {
                        switch (keys[i])
                        {
                            case PropertyKey.Key_Project:
                                {
                                    streamEx = new StreamEx();
                                    streamEx.Write(dates[i]);
                                    streamEx.Seek(0L, SeekOrigin.Begin);
                                    int num = streamEx.ReadInt();
                                    for (int l = 0; l < num; l++)
                                    {
                                        Project project = new Project();
                                        project.ReadFromStream(streamEx);
                                        list2.Add(project);
                                    }
                                    streamEx.Close();
                                    break;
                                }
                            case PropertyKey.Key_Sample:
                                {
                                    streamEx = new StreamEx();
                                    streamEx.Write(dates[i]);
                                    streamEx.Seek(0L, SeekOrigin.Begin);
                                    int num = streamEx.ReadInt();
                                    for (int k = 0; k < num; k++)
                                    {
                                        Sample sample = new Sample(customCount);
                                        sample.Project = list2[streamEx.ReadInt()];
                                        sample.ReadFromStream(streamEx);
                                        list.Add(sample);
                                    }
                                    streamEx.Close();
                                    break;
                                }
                            case PropertyKey.Key_Wells:
                                {
                                    streamEx = new StreamEx();
                                    streamEx.Write(dates[i]);
                                    streamEx.Seek(0L, SeekOrigin.Begin);
                                    int num = streamEx.ReadInt();
                                    for (int j = 0; j < num; j++)
                                    {
                                        Well well = wells[streamEx.ReadInt()];
                                        well.SetSample(list[streamEx.ReadInt()], well.MultiTubeID);
                                        well.Sample.Wells.Add(well);
                                        well.ReadFromStream(streamEx);
                                    }
                                    streamEx.Close();
                                    break;
                                }
                        }
                    }
                    return true;
                }
                stream.Seek(-4L, SeekOrigin.Current);
                return false;
            }
            stream.Seek(-4L, SeekOrigin.Current);
            while (true)
            {
                switch (stream.ReadKey())
                {
                    case PropertyKey.Key_Project:
                        {
                            int num2 = stream.ReadInt();
                            for (int n = 0; n < num2; n++)
                            {
                                Project project2 = new Project();
                                project2.ReadFromStream(stream);
                                list2.Add(project2);
                            }
                            break;
                        }
                    case PropertyKey.Key_Sample:
                        {
                            int num2 = stream.ReadInt();
                            for (int num3 = 0; num3 < num2; num3++)
                            {
                                Sample sample2 = new Sample(customCount);
                                sample2.Project = list2[stream.ReadInt()];
                                sample2.ReadFromStream(stream);
                                list.Add(sample2);
                            }
                            break;
                        }
                    case PropertyKey.Key_Wells:
                        {
                            int num2 = stream.ReadInt();
                            for (int m = 0; m < num2; m++)
                            {
                                Well well2 = wells[stream.ReadInt()];
                                well2.SetSample(list[stream.ReadInt()], well2.MultiTubeID);
                                well2.Sample.Wells.Add(well2);
                                well2.ReadFromStream(stream);
                            }
                            break;
                        }
                    default:
                        stream.Seek(-4L, SeekOrigin.Current);
                        return true;
                }
            }
        }

        private void RegisterDeviceRunEvent()
        {
            if (!_IsRegisterDeviceRunEvent)
            {
                _Device.RunStateEvent += _Device_RunStateEvent;
                _Device.SaveTempFileEvent += _Device_SaveTempFileEvent;
                _Device.RunErrorEvent += _Device_RunErrorEvent;
                _IsRegisterDeviceRunEvent = true;
            }
        }

        protected virtual void _Device_RunErrorEvent(object sender, EventArgs e)
        {
            if (_Device.RunError != 0)
            {
                DeleteTemporaryFile();
            }
        }

        private void InitModelAB()
        {
            _ModleAWells.Clear();
            _ModleBWells.Clear();
            for (int i = 0; i < _Wells.Count; i++)
            {
                if (i % 12 < 6)
                {
                    _ModleAWells.Add(_Wells[i]);
                }
                else
                {
                    _ModleBWells.Add(_Wells[i]);
                }
            }
        }

        private void UpdataSubsetAll()
        {
            List<Well> wells = null;
            if (_Device.Model == Device.DeviceModel_24P)
            {
                wells = _Wells.Where((Well s) => s.RowIndex < 3 && s.ColumnIndex < 8).ToList();
            }
            else if (_Device.Model == Device.DeviceModel_40P)
            {
                wells = _Wells.Where((Well s) => (_UseModelA && (s.CellName == "D3" || s.CellName == "D4" || s.CellName == "D5" || s.CellName == "D6")) || (_UseModelB && (s.CellName == "A7" || s.CellName == "A8" || s.CellName == "A9" || s.CellName == "A10"))).ToList();
            }
            else if (_UseModelA && _UseModelB)
            {
                wells = _Wells;
            }
            else if (_UseModelA)
            {
                wells = _ModleAWells;
            }
            else if (_UseModelB)
            {
                wells = _ModleBWells;
            }
            _Subsets[0] = new Subset
            {
                IsReadOnly = true,
                Name = "All",
                Wells = wells
            };
            CurrentSubset = _Subsets[0];
        }

        private void MustUseModelA()
        {
            if (_ModleAWells.Where((Well s) => s.Sample != null).Count() > 0)
            {
                UseModelA = true;
            }
            if (Type == EProjectType.Melt || Type == EProjectType.HRM || (!_UseModelA && !_UseModelB))
            {
                UseModelA = true;
            }
            if (_Device.Model == Device.DeviceModel_96S)
            {
                UseModelA = true;
            }
        }

        private void MustUseModelB()
        {
            if (_Device.Model == Device.DeviceModel_48P || _Device.Model == Device.DeviceModel_24P)
            {
                UseModelB = false;
                return;
            }
            if (_ModleBWells.Where((Well s) => s.Sample != null).Count() > 0)
            {
                UseModelB = true;
            }
            if (Type == EProjectType.Melt || Type == EProjectType.HRM || (!_UseModelA && !_UseModelB))
            {
                UseModelB = true;
            }
            if (_Device.Model == Device.DeviceModel_96S)
            {
                UseModelB = true;
            }
        }

        public void RefreshGirdColumns()
        {
            GridColumns = ConfigSettings.GetInstance().GetGirdColumnsClone(Type);
        }

        public bool CheckDatFile()
        {
            bool result = false;
            try
            {
                FileStream fileStream = new FileStream(datPath, FileMode.Open, FileAccess.Read);
                fileStream.Seek(indexSN - 1, SeekOrigin.Begin);
                byte[] array = new byte[4];
                fileStream.Read(array, 0, array.Length);
                int num = BitConverter.ToInt32(array, 0);
                array = new byte[num];
                fileStream.Read(array, 0, array.Length);
                string @string = Encoding.UTF8.GetString(array);
                @string = string.Concat(@string.ToCharArray().Reverse());
                fileStream.Seek(indexCompany - 1, SeekOrigin.Begin);
                array = new byte[4];
                fileStream.Read(array, 0, array.Length);
                num = BitConverter.ToInt32(array, 0);
                array = new byte[num];
                fileStream.Read(array, 0, array.Length);
                string string2 = Encoding.UTF8.GetString(array);
                fileStream.Close();
                string text = Utility.DecryptDES(string2, encryptKey);
                string text2 = Utility.DecryptDES(@string, encryptKey);
                string text3 = Device.Company.ToString();
                if (text == "0" || text == text3)
                {
                    result = true;
                }
                else if (text3 == "0")
                {
                    if (string.IsNullOrEmpty(text2))
                    {
                        result = true;
                    }
                    else
                    {
                        List<string> list = new List<string>(text2.Split(','));
                        if (list.IndexOf(Device.Series) > -1)
                        {
                            result = true;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        public bool ProjectChannelMatch(Project prj)
        {
            if (string.IsNullOrEmpty(Device.Series))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(prj.Target.Channels) && prj.Target.Channels.Split('&').Length == 6)
            {
                int i;
                for (i = 0; i < Device.ChannelNo.Count(); i++)
                {
                    string[] array = prj.Target.Channels.Split('&');
                    if (!(array[i] == "0") && prj.Target.Items.Where((TargetItem s) => s.ChannelNo == i + 1).Count() != 0 && array[i] != Device.ChannelNo[i].ToString())
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
